<template>
  <div class="page-container">
    <van-nav-bar 
      title="检控规则管理" 
      left-arrow 
      @click-left="router.back()"
    >
      <template #right>
        <van-icon name="plus" @click="router.push('/datacontrol/rules/create')" />
      </template>
    </van-nav-bar>

    <div class="content">
      <!-- 搜索筛选 -->
      <van-cell-group inset>
        <van-field
          v-model="searchForm.ruleName"
          label="规则名称"
          placeholder="请输入规则名称"
          clearable
          @clear="loadRules(true)"
          @keyup.enter="loadRules(true)"
        />
        <van-field
          v-model="searchForm.status"
          label="规则状态"
          placeholder="请选择状态"
          readonly
          is-link
          @click="showStatusPicker = true"
        />
        <van-field
          v-model="searchForm.publishStatus"
          label="发布状态"
          placeholder="请选择发布状态"
          readonly
          is-link
          @click="showPublishStatusPicker = true"
        />
        <van-cell>
          <template #title>
            <van-button type="primary" size="small" @click="loadRules(true)">搜索</van-button>
            <van-button size="small" style="margin-left: 8px;" @click="resetSearch">重置</van-button>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 规则列表 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell-group inset v-for="rule in rules" :key="rule.id" class="rule-item">
            <van-cell :title="rule.ruleName" :label="rule.ruleCode" is-link @click="viewRuleDetail(rule)">
              <template #extra>
                <div class="rule-actions">
                  <van-tag :type="getStatusType(rule.status)" size="small">{{ rule.statusText }}</van-tag>
                  <van-tag :type="getPublishStatusType(rule.publishStatus)" size="small" style="margin-top: 4px;">
                    {{ rule.publishStatusText }}
                  </van-tag>
                </div>
              </template>
            </van-cell>
            
            <van-cell>
              <template #title>
                <div class="rule-info">
                  <div>所属分组: {{ rule.groupName }}</div>
                  <div>优先级: {{ rule.rulePriority }}</div>
                  <div>适用年限: {{ rule.applicableYears }}</div>
                  <div>有效期: {{ rule.effectiveStartDate }}</div>
                  <div>更新时间: {{ formatDateTime(rule.updatedTime) }}</div>
                </div>
              </template>
            </van-cell>

            <!-- 操作按钮 -->
            <van-cell>
              <template #title>
                <div class="action-buttons">
                  <van-button size="mini" @click="editRule(rule)">编辑</van-button>
                  <van-button 
                    v-if="rule.publishStatus === 'UNPUBLISHED'" 
                    size="mini" 
                    type="success" 
                    @click="publishRule(rule)"
                  >
                    发布
                  </van-button>
                  <van-button 
                    v-if="rule.publishStatus === 'PUBLISHED'" 
                    size="mini" 
                    type="warning" 
                    @click="unpublishRule(rule)"
                  >
                    取消发布
                  </van-button>
                  <van-button 
                    v-if="rule.status === 'DISABLED'" 
                    size="mini" 
                    type="primary" 
                    @click="enableRule(rule)"
                  >
                    启用
                  </van-button>
                  <van-button 
                    v-if="rule.status === 'PUBLISHED'" 
                    size="mini" 
                    @click="disableRule(rule)"
                  >
                    禁用
                  </van-button>
                  <van-button size="mini" type="danger" @click="deleteRule(rule)">删除</van-button>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 状态选择器 -->
    <van-popup v-model:show="showStatusPicker" position="bottom">
      <van-picker
        :columns="statusOptions"
        @confirm="onStatusConfirm"
        @cancel="showStatusPicker = false"
      />
    </van-popup>

    <!-- 发布状态选择器 -->
    <van-popup v-model:show="showPublishStatusPicker" position="bottom">
      <van-picker
        :columns="publishStatusOptions"
        @confirm="onPublishStatusConfirm"
        @cancel="showPublishStatusPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { dataControlApi } from '@/api'

const router = useRouter()

// 响应式数据
const rules = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const showStatusPicker = ref(false)
const showPublishStatusPicker = ref(false)

// 搜索表单
const searchForm = reactive({
  ruleName: '',
  status: '',
  publishStatus: ''
})

// 分页参数
const pageParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 选择器选项
const statusOptions = [
  { text: '全部', value: '' },
  { text: '草稿', value: 'DRAFT' },
  { text: '已发布', value: 'PUBLISHED' },
  { text: '已禁用', value: 'DISABLED' }
]

const publishStatusOptions = [
  { text: '全部', value: '' },
  { text: '未发布', value: 'UNPUBLISHED' },
  { text: '已发布', value: 'PUBLISHED' }
]

// 加载规则列表
const loadRules = async (reset = false) => {
  if (reset) {
    pageParams.pageNo = 1
    rules.value = []
    finished.value = false
  }

  loading.value = true
  try {
    const params = {
      ...pageParams,
      ...searchForm
    }
    
    const response = await dataControlApi.getRuleList(params)
    
    if (reset) {
      rules.value = response.records
    } else {
      rules.value.push(...response.records)
    }
    
    // 判断是否还有更多数据
    finished.value = rules.value.length >= response.total
    
    if (!finished.value) {
      pageParams.pageNo++
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadRules(true)
}

// 上拉加载
const onLoad = () => {
  if (!finished.value) {
    loadRules()
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.ruleName = ''
  searchForm.status = ''
  searchForm.publishStatus = ''
  loadRules(true)
}

// 状态选择确认
const onStatusConfirm = ({ selectedOptions }) => {
  searchForm.status = selectedOptions[0].value
  showStatusPicker.value = false
  loadRules(true)
}

// 发布状态选择确认
const onPublishStatusConfirm = ({ selectedOptions }) => {
  searchForm.publishStatus = selectedOptions[0].value
  showPublishStatusPicker.value = false
  loadRules(true)
}

// 查看规则详情
const viewRuleDetail = (rule) => {
  router.push(`/datacontrol/rules/${rule.id}`)
}

// 编辑规则
const editRule = (rule) => {
  router.push(`/datacontrol/rules/${rule.id}/edit`)
}

// 发布规则
const publishRule = async (rule) => {
  try {
    await dataControlApi.publishRule(rule.id)
    showToast('发布成功')
    loadRules(true)
  } catch (error) {
    showToast('发布失败: ' + error.message)
  }
}

// 取消发布规则
const unpublishRule = async (rule) => {
  try {
    await dataControlApi.unpublishRule(rule.id)
    showToast('取消发布成功')
    loadRules(true)
  } catch (error) {
    showToast('取消发布失败: ' + error.message)
  }
}

// 启用规则
const enableRule = async (rule) => {
  try {
    await dataControlApi.enableRule(rule.id)
    showToast('启用成功')
    loadRules(true)
  } catch (error) {
    showToast('启用失败: ' + error.message)
  }
}

// 禁用规则
const disableRule = async (rule) => {
  try {
    await dataControlApi.disableRule(rule.id)
    showToast('禁用成功')
    loadRules(true)
  } catch (error) {
    showToast('禁用失败: ' + error.message)
  }
}

// 删除规则
const deleteRule = async (rule) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除规则"${rule.ruleName}"吗？`
    })
    
    await dataControlApi.deleteRule(rule.id)
    showToast('删除成功')
    loadRules(true)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('删除失败: ' + error.message)
    }
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'DRAFT': 'default',
    'PUBLISHED': 'success',
    'DISABLED': 'danger'
  }
  return typeMap[status] || 'default'
}

// 获取发布状态类型
const getPublishStatusType = (publishStatus) => {
  const typeMap = {
    'UNPUBLISHED': 'warning',
    'PUBLISHED': 'success'
  }
  return typeMap[publishStatus] || 'default'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadRules(true)
})
</script>

<style scoped>
.content {
  padding: 16px;
}

.rule-item {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.rule-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.rule-info {
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}

.rule-info div {
  margin-bottom: 4px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.van-cell-group {
  margin-bottom: 12px;
}
</style>
